package com.htjc.integral.common.util;

import java.io.IOException;

import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.HttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;

import javax.net.ssl.X509TrustManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

import java.security.cert.X509Certificate;

/**
 * https
 * @author Administrator
 *
 */
public class HttpsClientTools {
	private static Logger log = LoggerFactory.getLogger(HttpsClientTools.class);
	/**
	 * 
	 * @param url    
	 * @param jsonData  JSON格式的参数
	 * @return
	 * @throws Exception
	 */
	public static String doHttpsPost(String url, String jsonData) throws Exception {

		String result = "";

		CloseableHttpClient httpClient = createHttpsClient();
		try {
			HttpPost httppost = new HttpPost(url);
			StringEntity strentity = new StringEntity(jsonData, "utf-8");
			strentity.setContentEncoding("UTF-8");
			strentity.setContentType("application/json");
			httppost.setEntity(strentity);
			httppost.setHeader("Content-Type", "text/json;charset=UTF-8");
			CloseableHttpResponse response = httpClient.execute(httppost);
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity);
			EntityUtils.consume(entity);
			response.close();

		} catch (Exception e) {
			e.printStackTrace();
			log.error("HttpClientTools.getAnsRemoteHttpContent (url = " + url + ")", e);
			//
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				log.error("HttpClientTools.getAnsRemoteHttpContent (url = " + url + ")", e);
			}

		}

		return result;

	}

	@SuppressWarnings("deprecation")
	private static CloseableHttpClient createHttpsClient() throws Exception {
		X509TrustManager x509mgr = new X509TrustManager() {
			@Override
			public void checkClientTrusted(X509Certificate[] xcs, String string) {
			}

			@Override
			public void checkServerTrusted(X509Certificate[] xcs, String string) {
			}

			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};
		SSLContext sslContext = SSLContext.getInstance("TLS");
		sslContext.init(null, new TrustManager[] { x509mgr }, new java.security.SecureRandom());
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
				SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		return HttpClients.custom().setSSLSocketFactory(sslsf).build();
	}
	
}
